
<script setup>
import { ref, onMounted } from 'vue';
import service from "@/api/request0.js";
import {useRoute} from "vue-router";

const orders = ref([]);
const errorMessage = ref('');
const route = useRoute()


const fetchOrders = async () => {
  try {
    const response = await service.get(`/order/getOrdersByUserId/${route.params.userId}`)
    orders.value = response;
  } catch (error) {
    if (error.response) {
      errorMessage.value = `HTTP 错误: ${error.response.status}`;
    } else if (error.request) {
      errorMessage.value = '没有收到服务器响应';
    } else {
      errorMessage.value = `错误: ${error.message}`;
    }
    console.error('Failed to fetch orders:', error);
  }
};

const deleteOrder = async (orderId) => {
  try {
    await service.delete(`/order/getOrdersByUserId/delete/${orderId}`);
    // 从本地数据中移除该订单
    await fetchOrders();
  } catch (error) {
    if (error.response) {
      errorMessage.value = `HTTP 错误: ${error.response.status}`;
    } else if (error.request) {
      errorMessage.value = '没有收到服务器响应';
    } else {
      errorMessage.value = `错误: ${error.message}`;
    }
    console.error('Failed to delete order:', error);
  }
};

// 在组件挂载时调用fetchOrders
onMounted(fetchOrders);
</script>

<template>
  <div>
    <h1>当前用户所有订单</h1>
    <ul >
      <li v-for="order in orders" :key="order.orderId" class="order-item">
        <p>订单号: {{ order.orderId }}</p>
        <p>订单日期: {{ order.orderDate }}</p>
        <p>订单总价: {{ order.totalPrice }}</p>
        <button @click="deleteOrder(order.orderId)">删除订单</button>
      </li>
    </ul>

    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
  </div>
</template>

<style scoped>

ul {
  list-style-type: none;
  padding: 0;
}

li {
  border: 1px solid #ccc;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
}

h1 {
  text-align: center;
}

.order-item {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 15px;
}

.error-message {
  color: red;
  font-weight: bold;
}
</style>